package com.beiing.tianshuai.tianshuai.mine.ui;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.RelativeLayout;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.adapter.OrderManageAddressAdapter;
import com.beiing.tianshuai.tianshuai.app.AppConstant;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.mine.entity.OrderUserAddressDataBean;
import com.beiing.tianshuai.tianshuai.mine.entity.OrderUserAddressDefaultDataBean;
import com.beiing.tianshuai.tianshuai.mine.entity.OrderUserAddressDeleteDataBean;
import com.beiing.tianshuai.tianshuai.mine.presenter.OrderAddressManagePresenter;
import com.beiing.tianshuai.tianshuai.mine.view.OrderAddressManageViewImpl;
import com.beiing.tianshuai.tianshuai.widget.CustomDialog;

import java.util.List;

import butterknife.BindView;

/**
 * 管理订单地址
 *
 * @author Administrator
 */
public class
OrderAddressManageActivity extends BaseActivity implements OrderAddressManageViewImpl {

    /**
     * toolbar返回按钮
     */
    @BindView(R.id.toolbar_navigation_back)
    ImageButton toolbarNavigationBack;

    /**
     * 添加地址布局按钮
     */
    @BindView(R.id.rl_add_address)
    RelativeLayout rlAddAddress;

    /**
     *
     */
    @BindView(R.id.rlv_order_manage_address)
    RecyclerView rvAddressList;

    /**
     * order address manage presenter
     */
    private OrderAddressManagePresenter mPresenter;

    /**
     * order manager address adapter
     */
    private OrderManageAddressAdapter mAdapter;

    /**
     * 地址id
     */
    private String mAddressId = null;

    /**
     * 用户id
     */
    private String mUserId = UserInfoBean.getUid(mContext);

    @Override
    protected int getLayoutId() {
        return R.layout.activity_order_manage_address;
    }

    @Override
    protected void init() {
        mUserId = UserInfoBean.getUid(mContext);
        initRecyclerView();
        initPresenter();
        initListener();
    }

    /**
     * 初始化 recycler view
     */
    private void initRecyclerView() {
        //创建LinearLayoutManager 对象
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        //设置RecyclerView 布局
        rvAddressList.setLayoutManager(mLayoutManager);
        //设置Adapter
        mAdapter = new OrderManageAddressAdapter(mContext);
        rvAddressList.setAdapter(mAdapter);
    }

    /**
     * 初始化监听事件
     */
    private void initListener() {
        //添加地址按钮
        rlAddAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, OrderAddressEditActivity.class);
                intent.putExtra("isEditAddress", false);
                startActivityForResult(intent, AppConstant.REQUEST_CODE_EDIT_RECEIVE_ADDRESS);
            }
        });

        //返回按钮
        toolbarNavigationBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //返回键执行
                //onBackPressed();
//                if (!TextUtils.isEmpty(mAddressId)) {
//                    mPresenter.getUserAddressDef(mUserId, mAddressId);
//                }
                //需要执行默认地址修改
                //返回结果码给选择界面
                Intent intent = getIntent();
                setResult(AppConstant.RESULT_CODE_EDIT_RECEIVE_ADDRESS, intent);
                finish();
            }
        });
        /**
         * 默认地址修改
         */
        mAdapter.buttonSetOnclick(new OrderManageAddressAdapter.OnItemButtonClickListener() {
            @Override
            public void onclick(OrderUserAddressDataBean.DataBean.AddressBean bean, int position) {
                //showShortText("点击了item中的状态按钮");
                mAddressId = bean.getId();
                mUserId = bean.getUserId();
                //showShortText("设置" + mAddressId + "用户" + mUserId);
                List<OrderUserAddressDataBean.DataBean.AddressBean> list = mAdapter.getList();
                OrderUserAddressDataBean.DataBean.AddressBean addressChangeDataBean=new OrderUserAddressDataBean.DataBean.AddressBean();
                OrderUserAddressDataBean.DataBean.AddressBean addressChangeAfterDataBean=new OrderUserAddressDataBean.DataBean.AddressBean();
                // 找到当前默认的地址，设置它的选择状态为false
                for (OrderUserAddressDataBean.DataBean.AddressBean addressBean : list) {
                    if (addressBean.isSelected()) {
                        addressBean.setSelected(false);
                        addressChangeDataBean=addressBean;
                        break;
                    }
                }
                // 设置当前用户选择的item，设置他的选择状态为true
                list.get(position).setSelected(true);
                addressChangeAfterDataBean=list.get(position);
                //直接进行网络请求
                mPresenter.getUserAddressDef(mUserId,mAddressId,addressChangeDataBean,addressChangeAfterDataBean);
                //mAdapter.notifyDataSetChanged();
            }

            /**
             * 编辑监听事件
             * @param bean 数据
             * @param position 标签
             */
            @Override
            public void onEditClick(OrderUserAddressDataBean.DataBean.AddressBean bean, int position) {
                //showShortText("点击了item中的编辑按钮");
                //将数据传递到编辑界面
                OrderAddressEditActivity.start(mContext, bean.getId(), bean.getTruename(),
                        bean.getTelephone(), bean.getAddress(), bean.getProvince(), bean.getCity(),
                        bean.getCounty(), bean.getProvince() + bean.getCity() + bean.getCounty(),
                        bean.getLabel(), bean.getDef());
                //mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onDeleteClick(final OrderUserAddressDataBean.DataBean.AddressBean bean, final int position) {
                CustomDialog dialog = new CustomDialog(mContext, R.style.dialog, "确认删除这个地址吗？", new CustomDialog.OnCloseListener() {
                    @Override
                    public void onClick(Dialog dialog, boolean confirm) {
                        if (confirm) {
                            mPresenter.getUserAddressDel(bean.getId(), position);
                            dialog.dismiss();
                        } else {
                            dialog.dismiss();
                        }
                    }
                }).setNegativeButton("取消").setPositiveButton("确认").setTitle("提示");
                dialog.setCanceledOnTouchOutside(true);
                dialog.show();
            }
        });
    }

    /**
     * 自动更新数据
     */
    @Override
    protected void onResume() {
        super.onResume();
        //更新数据
        initPresenter();
    }

    /**
     * 跳转到管理地址页面
     *
     * @param context 强转的
     */
    public static void start(Context context) {
        Intent intent = new Intent(context, OrderAddressManageActivity.class);
        //强转返回参数,请求码
        ((Activity) context).startActivityForResult(intent, AppConstant.REQUEST_CODE_MANAGE_RECEIVE_ADDRESS);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Log.i("调用了onActivityResult", "1234==========================");

        //请求码
        switch (requestCode) {
            case AppConstant.REQUEST_CODE_MANAGE_RECEIVE_ADDRESS:
                //结果码
                switch (resultCode) {
                    case AppConstant.RESULT_CODE_MANAGE_RECEIVE_ADDRESS:
                        //刷新数据
                        Log.i("获取到了请求码" + AppConstant.RESULT_CODE_MANAGE_RECEIVE_ADDRESS, "1234");
                        if (mPresenter == null) {
                            mPresenter = new OrderAddressManagePresenter(this);
                        }
                        //重新拉取数据
                        mPresenter.getUserAddress(UserInfoBean.getUid(mContext));
                        break;
                    default:
                        break;
                }
                break;
            default:
                break;
        }
    }

    /**
     * 要请求的用户id
     */
    public void initPresenter() {
        mPresenter = new OrderAddressManagePresenter(this);
        mPresenter.getUserAddress(UserInfoBean.getUid(mContext));
    }

    @Override
    public void showProgress() {

    }

    @Override
    public void hideProgress() {

    }

    @Override
    public void onRequestSuccess(OrderUserAddressDataBean bean) {

    }

    @Override
    public void onRequestFailed(Throwable throwable) {

    }

    /**
     * 用户地址数据获取成功
     */
    @Override
    public void getOrderInformationAddressSuccess(OrderUserAddressDataBean bean) {
        int code = bean.getCode();
        switch (code) {
            case 200:
                OrderUserAddressDataBean.DataBean data = bean.getData();
                List<OrderUserAddressDataBean.DataBean.AddressBean> mList = data.getAddress();
                for (OrderUserAddressDataBean.DataBean.AddressBean addressBean : mList) {
                    if (TextUtils.equals(addressBean.getDef(), "1")) {
                        addressBean.setSelected(true);
                        break;
                    }
                }
                mAdapter.updateData(mList);
                break;
            case 401:
                showShortText("参数错误");
                break;
            case 202:
                mAdapter.notifyDataSetChanged();
                showShortText("没有数据");
                break;
            default:
                break;
        }
    }

    @Override
    public void getOrderInformationAddressError(OrderUserAddressDataBean bean) {

    }

    /**
     *     用户修改默认值返回参数获取成功
     */
    @Override
    public void getOrderDefaultInformationSuccess(OrderUserAddressDefaultDataBean bean, OrderUserAddressDataBean.DataBean.AddressBean changeBean,
                                                  OrderUserAddressDataBean.DataBean.AddressBean changeAfterBean) {
        int code = bean.getCode();
        switch (code) {
            case 200:
                //showShortText("修改默认收货地址成功");
                //手动更改def,传递的位置
                changeBean.setDef("0");
                changeAfterBean.setDef("1");

                mAdapter.notifyDataSetChanged();
                break;
            case 401:
                showShortText("参数错误");
                break;
            default:
                break;
        }
    }

    @Override
    public void getOrderDefaultInformationError(OrderUserAddressDefaultDataBean bean) {
        showShortText("修改默认收货地址失败");
    }

    /**
     * 用户删除地址成功返回参数
     */
    @Override
    public void onDeleteSuccess(OrderUserAddressDeleteDataBean bean, int position) {
        int code = bean.getCode();
        switch (code) {
            case 200:
                mAdapter.removeData(position);
                break;
            case 401:
                showShortText("参数错误");
                break;
            default:
                break;
        }
    }

    @Override
    public void getOrderDeleteInformationError(OrderUserAddressDeleteDataBean bean) {

    }
}
